﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.CodeDom;
using System.Reflection;
using System.ComponentModel.Composition;

namespace NeuroSpeech.XamlExtensions
{
    [Export]
    public class EventConverter : DefaultConverter
    {


        #region public override bool  CanProcess(XamlCodeContext context)
        public override bool CanProcess(XamlCodeContext context)
        {
            if (context.Peek.IsMemberEvent)
                return true;
            return base.CanProcess(context);
        }
        #endregion


        #region public override System.CodeDom.CodeStatement  Assign(XamlCodeContext context, System.CodeDom.CodeExpression target, System.CodeDom.CodeExpression value)
        public override CodeStatement Assign(XamlCodeContext context, CodeExpression target, CodeExpression value)
        {
            CodeEventReferenceExpression ce = new CodeEventReferenceExpression { 
                TargetObject = context.ParentTarget(target),
                EventName = context.Member.Name
            };
            EventInfo ei = context.Peek.MemberEvent;
            CodeAttachEventStatement att = new CodeAttachEventStatement
            {
                Event = ce,
                Listener = new CodeDelegateCreateExpression { 
                    DelegateType = new CodeTypeReference( ei.EventHandlerType),
                    TargetObject = new CodeThisReferenceExpression(),
                    MethodName = context.Peek.Value.Value as string
                }
            };
            return att;
        }
        #endregion


    }
}
